package com.yunshipei.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.common.Globals;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.ShareInfoModel;
import com.yunshipei.model.ShareItemEnum;
import com.yunshipei.model.ShareModel;
import com.yunshipei.utils.CharacterParser;
import com.yunshipei.utils.ShareUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.app.DemoContext;
import io.rong.app.adapter.GroupListAdapter;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.ui.WinToast;
import io.rong.app.utils.Constants;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;

public class GroupListActivity extends BaseActivity implements AdapterView.OnItemClickListener, OnClickListener, ShareUtil.OnSendMessageSuccessListener {
    private ListView mGroupListView;
    private GroupListAdapter mDemoGroupListAdapter;
    private List<GroupCreateInfo> mResultList;
    private List<GroupCreateInfo> cloneResultList;
    private UpdateGroupBroadcastReciver mBroadcastReciver;
    private Map<String, Group> mGroupMap;
    private GroupCreateInfo result;
    private SharedPreferences mySharedPreferences = null;
    private YspTitleBar mTitleBar;
    private EditText searchEdit;
    private ShareInfoModel shareInfoModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_list);
        mySharedPreferences = getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
        initView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MainActivity.ACTION_DMEO_GROUP_MESSAGE);
        if (mBroadcastReciver == null) {
            mBroadcastReciver = new UpdateGroupBroadcastReciver();
        }
        this.registerReceiver(mBroadcastReciver, intentFilter);
        mGroupListView.setOnItemClickListener(this);
        initData();
    }

    private void initView() {
        searchEdit = (EditText) findViewById(R.id.share_search);
        mTitleBar = (YspTitleBar) findViewById(R.id.title_bar);
        mTitleBar.setTitle(getResources().getString(R.string.main_group));
        mGroupListView = (ListView) findViewById(R.id.de_group_list);
        mGroupListView.setItemsCanFocus(false);
        mGroupListView.setEmptyView(findViewById(R.id.group_list_empty));
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.d("GroupListActivity", "onResume");
        mGroupMap = DemoContext.getInstance(GroupListActivity.this).getGroupMap();
        mResultList = DemoContext.getInstance(GroupListActivity.this).getResult();
        cloneResultList = new ArrayList<>(mResultList);
        mDemoGroupListAdapter.notifyDataSetChanged();
        initData();
        initSearchEvent();
    }

    private void initData() {
        Intent intent = getIntent();
        if (Globals.SHARE.equals(intent.getAction())) {
            searchEdit.setVisibility(View.VISIBLE);
            Bundle bundle = getIntent().getBundleExtra("shareInfoModel");
            shareInfoModel = (ShareInfoModel) bundle.getSerializable("shareInfoModel");
        }
        mResultList = new ArrayList<GroupCreateInfo>();
        if (DemoContext.getInstance(GroupListActivity.this) != null) {
            mResultList = (new DatabaseUtil()).queryGroups();
            cloneResultList = new ArrayList<>(mResultList);
            //群组列表适配器
            mDemoGroupListAdapter = new GroupListAdapter(GroupListActivity.this, mResultList);
            mGroupListView.setAdapter(mDemoGroupListAdapter);
            mDemoGroupListAdapter.setOnItemButtonClick(new GroupListAdapter.OnItemButtonClick() {
                @Override
                public boolean onButtonClick(int position, View view) {
                    result = mDemoGroupListAdapter.getItem(position);
                    if (result == null)
                        return false;
                    if (mGroupMap.containsKey(result.getId()) && mySharedPreferences.getBoolean("RCSconnectStatus", false)) {
                        //进入群聊界面
                        RongIM.getInstance().startGroupChat(GroupListActivity.this, result.getId(), result.getName());
                        finish();
                    } else {
                        Toast.makeText(GroupListActivity.this, "IM功能暂时不可用", Toast.LENGTH_LONG).show();
                    }
                    return true;
                }
            });
            //群组列表信息变动更新
            mDemoGroupListAdapter.notifyDataSetChanged();
        }
    }

    private void initSearchEvent() {
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SearchTask searchTask = new SearchTask();
                searchTask.execute(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onClick() {
        setResult(ShareActivity.RESPONSE_CODE);
        GroupListActivity.this.finish();
        Toast.makeText(GroupListActivity.this, "已发送", Toast.LENGTH_SHORT).show();
    }

    private class UpdateGroupBroadcastReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(MainActivity.ACTION_DMEO_GROUP_MESSAGE)) {
                initData();
                Log.e("GroupListActivity", "---push----UpdateGroupBroadcastReciver---");
            }
        }
    }

    public void onDestroy() {
        if (mDemoGroupListAdapter != null) {
            mDemoGroupListAdapter = null;
        }
        if (mBroadcastReciver != null) {
            this.unregisterReceiver(mBroadcastReciver);
        }
        super.onDestroy();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (getIntent() != null && Globals.SHARE.equals(getIntent().getAction())) {
            Bundle bundle = getIntent().getBundleExtra("shareInfoModel");
            shareInfoModel = (ShareInfoModel) bundle.getSerializable("shareInfoModel");
            ShareModel shareModel = new ShareModel();
            result = (GroupCreateInfo) parent.getAdapter().getItem(position);
            shareModel.setNember(result.getNumber());
            shareModel.setTargetId(result.getId());
            shareModel.setAvator(result.getPortraitUri());
            shareModel.setName(result.getName());
            shareModel.setItemType(ShareItemEnum.GROUP);
            shareInfoModel.setShareModel(shareModel);
            shareInfoModel.setType(Conversation.ConversationType.GROUP);
            ShareUtil shareUtil = new ShareUtil(GroupListActivity.this);
            shareUtil.setData(shareInfoModel);
            shareUtil.setOnDefineClickLisenter(this);
            shareUtil.showDialog();
        } else if (mResultList != null && position != -1 && position < mResultList.size()) {
            result = mDemoGroupListAdapter.getItem(position);
            if (result != null && mGroupMap.containsKey(result.getId())) {
                //进入群聊界面
                RongIM.getInstance().startGroupChat(GroupListActivity.this, result.getId(), result.getName());
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constants.GROUP_JOIN_REQUESTCODE:
            case Constants.GROUP_QUIT_REQUESTCODE:
                Toast.makeText(GroupListActivity.this, "onActivityResult---status", Toast.LENGTH_SHORT).show();
                updateAdapter();
                initData();
                break;
        }


    }

    private void updateAdapter() {
        Log.e("", "------updateAdapter------");
        if (mDemoGroupListAdapter != null) {
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            HashMap<String, Group> newGroupMap = new HashMap<>();
            List<GroupCreateInfo> newResultList = new ArrayList<>();
            newGroupMap = (HashMap<String, Group>) bundle.get("result1");
            newResultList = (List<GroupCreateInfo>) bundle.get("result2");
            mGroupMap = newGroupMap;
            mResultList = newResultList;
            mDemoGroupListAdapter = new GroupListAdapter(GroupListActivity.this, newResultList);
            mGroupListView.setAdapter(mDemoGroupListAdapter);
            mDemoGroupListAdapter.setOnItemButtonClick(new GroupListAdapter.OnItemButtonClick() {
                @Override
                public boolean onButtonClick(int position, View view) {
                    result = mDemoGroupListAdapter.getItem(position);
                    if (result == null)
                        return true;
                    if (mGroupMap.containsKey(result.getId())) {
                        RongIM.getInstance().startGroupChat(GroupListActivity.this, result.getId(), result.getName());
                    } else {
                        if (DemoContext.getInstance(GroupListActivity.this) != null) {
                            if (result.getNumber() == 500) {
                                WinToast.toast(GroupListActivity.this, "群组人数已满");
                                return true;
                            }
                        }
                    }
                    return true;
                }
            });
        } else {
            mDemoGroupListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.back:
            case R.id.upClass:
                finish();
                break;
            default:
                finish();
                break;
        }
    }

    private class SearchTask extends AsyncTask<String, Void, List<GroupCreateInfo>> {
        @Override
        protected List<GroupCreateInfo> doInBackground(String... params) {
            String searchKey = params[0];
            List<GroupCreateInfo> filterDateList1 = new ArrayList<GroupCreateInfo>();
            if (TextUtils.isEmpty(searchKey)) {
                filterDateList1 = new ArrayList<>(cloneResultList);
            } else {
                filterDateList1.clear();
                for (GroupCreateInfo groupCreateInfo : mResultList) {
                    String name = groupCreateInfo.getName();
                    if (!TextUtils.isEmpty(name) && compare(name, searchKey.toString())) {
                        if (!verdictSame(filterDateList1, groupCreateInfo)) {
                            filterDateList1.add(groupCreateInfo);
                        }
                    }
                }
            }
            return filterDateList1;
        }

        @Override
        protected void onPostExecute(List<GroupCreateInfo> filterDateList1) {
            mDemoGroupListAdapter.clear();
            mDemoGroupListAdapter.addCollection(filterDateList1);
            mDemoGroupListAdapter.notifyDataSetChanged();
        }
    }

    private boolean compare(String str1, String str2) {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.indexOf(str2.toString()) != -1 || CharacterParser.getInstance().getSelling(str1).startsWith(str2.toString())) {
            return true;
        }
        return false;
    }

    private boolean verdictSame(List<GroupCreateInfo> list, GroupCreateInfo groupCreateInfo) {
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (list.get(i).getId().equals(groupCreateInfo.getId())) {
                return true;
            }
        }
        return false;
    }

}
